import { message } from 'antd';

// API基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api';

// 通用请求函数
export const request = async (url, options = {}) => {
  const token = localStorage.getItem('token');
  
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      ...(token && { Authorization: `Bearer ${token}` }),
      ...options.headers,
    },
  };

  const config = {
    ...defaultOptions,
    ...options,
    headers: {
      ...defaultOptions.headers,
      ...options.headers,
    },
  };

  try {
    const response = await fetch(`${API_BASE_URL}${url}`, config);
    const data = await response.json();

    if (!response.ok) {
      // 处理401未授权错误
      if (response.status === 401) {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = '/login';
        throw new Error('登录已过期，请重新登录');
      }
      
      // 处理403权限不足错误
      if (response.status === 403) {
        message.error('权限不足');
        throw new Error('权限不足');
      }
      
      throw new Error(data.message || '请求失败');
    }

    return data;
  } catch (error) {
    console.error('API请求错误:', error);
    throw error;
  }
};

// 学生管理API
export const studentAPI = {
  // 获取学生列表
  getStudents: (params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/student?${queryString}`);
  },

  // 获取学生详情
  getStudentDetail: (id) => {
    return request(`/student/${id}`);
  },

  // 获取学生课时详情
  getStudentLessons: (id, params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/student/${id}/lessons?${queryString}`);
  },

  // 获取学生统计报表
  getStudentReport: (id, params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/student/${id}/report?${queryString}`);
  },

  // 获取课时回放链接
  getLessonReplay: (studentId, courseId, lessonId) => {
    return request(`/student/${studentId}/courses/${courseId}/lessons/${lessonId}/replay`);
  },
};

// 课时管理API
export const lessonAPI = {
  // 获取课程课时列表
  getCourseLessons: (courseId, params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/lesson/courses/${courseId}/lessons?${queryString}`);
  },

  // 获取课时详情和回放链接
  getLessonDetail: (courseId, lessonId, params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/lesson/courses/${courseId}/lessons/${lessonId}?${queryString}`);
  },

  // 更新观看进度
  updateWatchProgress: (courseId, lessonId, data) => {
    return request(`/lesson/courses/${courseId}/lessons/${lessonId}/progress`, {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },

  // 获取学生观看统计
  getStudentWatchStats: (studentId, params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/lesson/students/${studentId}/watch-stats?${queryString}`);
  },
};

// 课程API
export const courseAPI = {
  // 获取课程列表
  getCourses: (params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/course?${queryString}`);
  },

  // 获取课程详情
  getCourseDetail: (id) => {
    return request(`/course/${id}`);
  },

  // 获取我的课程
  getMyCourses: (params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/course/my-courses?${queryString}`);
  },

  // 获取推荐课程
  getRecommendedCourses: (params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/course/recommended?${queryString}`);
  },

  // 获取热门课程
  getHotCourses: (params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/course/hot?${queryString}`);
  },
};

// 用户API
export const userAPI = {
  // 用户登录
  login: (data) => {
    return request('/auth/login', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },

  // 用户注册
  register: (data) => {
    return request('/auth/register', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },

  // 获取用户信息
  getProfile: () => {
    return request('/user/profile');
  },

  // 更新用户信息
  updateProfile: (data) => {
    return request('/user/profile', {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  },

  // 修改密码
  changePassword: (data) => {
    return request('/user/password', {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  },

  // 退出登录
  logout: () => {
    return request('/auth/logout', {
      method: 'POST',
    });
  },
};

// 认证API (别名，向后兼容)
export const authAPI = userAPI;

// 文件上传API
export const uploadAPI = {
  // 上传文件
  uploadFile: (file, onProgress) => {
    const formData = new FormData();
    formData.append('file', file);

    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      
      xhr.upload.addEventListener('progress', (event) => {
        if (event.lengthComputable && onProgress) {
          const percentComplete = (event.loaded / event.total) * 100;
          onProgress(percentComplete);
        }
      });

      xhr.addEventListener('load', () => {
        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText);
            resolve(response);
          } catch {
            reject(new Error('响应解析失败'));
          }
        } else {
          reject(new Error(`上传失败: ${xhr.status}`));
        }
      });

      xhr.addEventListener('error', () => {
        reject(new Error('网络错误'));
      });

      xhr.open('POST', `${API_BASE_URL}/upload`);
      
      const token = localStorage.getItem('token');
      if (token) {
        xhr.setRequestHeader('Authorization', `Bearer ${token}`);
      }
      
      xhr.send(formData);
    });
  },
};

// 统计API
export const statisticsAPI = {
  // 获取总体统计
  getOverallStats: () => {
    return request('/statistics/overall');
  },

  // 获取用户统计
  getUserStats: (params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/statistics/users?${queryString}`);
  },

  // 获取课程统计
  getCourseStats: (params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/statistics/courses?${queryString}`);
  },
};

// 通知API
export const notificationAPI = {
  // 获取通知列表
  getNotifications: (params = {}) => {
    const queryString = new URLSearchParams(params).toString();
    return request(`/notification?${queryString}`);
  },

  // 标记通知为已读
  markAsRead: (id) => {
    return request(`/notification/${id}/read`, {
      method: 'PUT',
    });
  },

  // 删除通知
  deleteNotification: (id) => {
    return request(`/notification/${id}`, {
      method: 'DELETE',
    });
  },
};

export default {
  studentAPI,
  lessonAPI,
  courseAPI,
  userAPI,
  authAPI,
  uploadAPI,
  statisticsAPI,
  notificationAPI,
}; 